/*
RetroLeague - Mobile application for The Retro League Podcast
Copyright (C) 2010-2012 Hugues Johnson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.retroleague;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.huguesjohnson.retroleague.forums.ForumParser;
import com.huguesjohnson.retroleague.forums.ForumPost;
import com.huguesjohnson.retroleague.forums.ForumPostArrayAdapter;
import com.huguesjohnson.retroleague.util.SerializationHelper;

public class ForumPostListActivity extends Activity{
	private final static String TAG="ForumPostListActivity";
	private ArrayList<ForumPost> forumPosts;
	//ui stuff
	private AlertDialog aboutDialog;
	private ProgressBar progressBarRetrievingForumPosts;
	private TextView textViewRetrievingForumPosts;
	//menu constants
	private final static int MENU_BACK=0;
	private final static int MENU_ABOUT=1;
	private final static int MENU_REFRESH=2;
	//currently playing episode - needs to be accessible to ViewForumPostActivity
	private static ForumPost selectedPost;
	public static void setSelectedPost(ForumPost fp){selectedPost=fp;}
	public static ForumPost getSelectedPost(){return(selectedPost);}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		try{
			menu.add(0,MENU_ABOUT,0,"About").setIcon(R.drawable.menu_about);
			menu.add(0,MENU_REFRESH,1,"Refresh").setIcon(R.drawable.menu_refresh);
			menu.add(0,MENU_BACK,2,"Back to main menu").setIcon(R.drawable.menu_back);
			return(true);
		}catch(Exception x){
			Log.e(TAG,"onCreateOptionsMenu",x);
			return(false);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		try{
			switch(item.getItemId()){
			case MENU_REFRESH:{this.refreshForumPostList();return(true);}
			case MENU_ABOUT:{this.showAboutDialog(); return(true);}
			case MENU_BACK:{this.finish();return(true);}
			default:{return(false);}
			}
		}catch(Exception x){
			if(item!=null){
				Log.e(TAG,"onOptionsItemSelected: item.getItemId()="+item.getItemId(),x);
			}else{
				Log.e(TAG,"onOptionsItemSelected: item is null",x);
			}
			return(false);
		}
	}
	
	OnItemClickListener selectForumPostListener=new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> parent,View view,int position,long id){
			try{
				postClicked(position);
			}catch(Exception x){
				Log.e(TAG,"onItemClick: position="+position,x);
				showErrorDialog(x);
			}
		}
	};
	
	
	private class LoadForumPostListTask extends AsyncTask<String,String,Void>{
		public Void doInBackground(String... params){
        	HttpURLConnection httpConnection=null;
        	InputStream httpIn=null;
        	try{
        		long startTime=System.currentTimeMillis();
        		URL url=new URL(getResources().getString(R.string.forum_rss));
                httpConnection=(HttpURLConnection)url.openConnection();
                httpConnection.setConnectTimeout(10000);
        		long endTime=System.currentTimeMillis();
                Log.d(TAG,"Time to open connection="+(endTime-startTime)+"ms");
                startTime=endTime;
                httpIn=httpConnection.getInputStream();
        		endTime=System.currentTimeMillis();
                Log.d(TAG,"Time to get input stream="+(endTime-startTime)+"ms");
                startTime=endTime;
                forumPosts=ForumParser.parseForumPosts(httpIn);
        		endTime=System.currentTimeMillis();
                Log.d(TAG,"Time to parse episode list="+(endTime-startTime)+"ms");
                httpIn.close();
        		httpConnection.disconnect();
            }catch(Exception x){
    			Log.e(TAG,"LoadForumPostListThread.run",x);
            	//in case the IOException is thrown by one of the HttpURLConnection operations
            	if(httpConnection!=null){
            		httpConnection.disconnect();
            	}
            }
    		return(null);
	     }

	     @SuppressWarnings("unchecked")
		public void onPostExecute(Void result){
    		if((forumPosts!=null)&&(forumPosts.size()>0)){
    			updateUI();
    			SerializationHelper.serializeObject(forumPosts,"forumposts.obj");
    		}else{ //some kind of problem getting the episodes, revert to most recent good copy
        		ArrayList<ForumPost> cachedEpisodes=(ArrayList<ForumPost>)SerializationHelper.readObject("forumposts.obj");
        		if(cachedEpisodes!=null){
        			forumPosts=cachedEpisodes;
        			updateUI();
        		}else{
        			showErrorDialog(new Exception("Unable to download forum posts list. Please check your internet connectivity and retry."));
        			return;
        		}
    		}
    	}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forumpostlistlayout);
        ListView listViewForumPosts=(ListView)findViewById(R.id.ListViewForumPosts);
        listViewForumPosts.setOnItemClickListener(selectForumPostListener);
    	this.progressBarRetrievingForumPosts=(ProgressBar)findViewById(R.id.ProgressBarRetrievingForumPosts);
    	this.textViewRetrievingForumPosts=(TextView)findViewById(R.id.TextViewRetrievingForumPosts);
    }
    
    private void refreshForumPostList(){
		//launch a dialog and thread
		try{
			this.textViewRetrievingForumPosts.setVisibility(View.VISIBLE);
			this.progressBarRetrievingForumPosts.setVisibility(View.VISIBLE);
			this.textViewRetrievingForumPosts.setText(this.getResources().getString(R.string.status_forum_retrieving));
			new LoadForumPostListTask().execute("");
		}catch(Exception x){
			Log.e(TAG,"onResume",x);
			this.showErrorDialog(x);
		}
	}
    
	@Override
	protected void onResume(){
		super.onResume();
		//in case we came here after the user navigated away by clicking on the site link in the about dialog
		if((aboutDialog!=null)&&(aboutDialog.isShowing())){
			return;
		}
		//load the episode list
		if((this.forumPosts==null)||(this.forumPosts.size()<1)){
			this.refreshForumPostList();
		}
	}
	
	private void updateUI(){
		if((this.forumPosts==null)||(this.forumPosts.size()<1)){
			this.showErrorDialog(new Exception("No forum posts found,"));
		}else{ 
			this.textViewRetrievingForumPosts.setVisibility(View.GONE);
			this.progressBarRetrievingForumPosts.setVisibility(View.GONE);
			//show list of recent posts
			ForumPostArrayAdapter adapter=new ForumPostArrayAdapter(this.getApplicationContext(),R.layout.forumpostlistitem,this.forumPosts);
			ListView listViewForumPosts=(ListView)findViewById(R.id.ListViewForumPosts);
			listViewForumPosts.setAdapter(adapter);
		}
	}
	
	private void postClicked(int postIndex){
		try{
			setSelectedPost(this.forumPosts.get(postIndex));
			Intent viewForumPostIntent=new Intent(this.getApplicationContext(),ViewForumPostActivity.class);
			this.startActivityForResult(viewForumPostIntent,0);
		}catch(Exception x){
			Log.e(TAG,"postClicked, postIndex="+postIndex,x);
			this.showErrorDialog(x);
		}
	}
    
	private void showErrorDialog(Exception x){
		try{
	        new AlertDialog.Builder(this)
	   		.setTitle(R.string.app_name)
	   		.setMessage(x.getMessage())
	   		.setPositiveButton("Close", null)
	   		.show();	
		}catch(Exception reallyBadTimes){
			Log.e(TAG,"showErrorDialog",reallyBadTimes);
		}
	}
	
	private void showAboutDialog(){
		try{
			//create the dialog
			if(this.aboutDialog==null){
				LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout=inflater.inflate(R.layout.aboutdialoglayout,(ViewGroup)findViewById(R.id.AboutDialogRoot));
				AlertDialog.Builder builder=new AlertDialog.Builder(this);
				builder.setView(layout);
				builder.setTitle("About");
				builder.setPositiveButton("Close",null);
				this.aboutDialog=builder.create();
			}
			//show the dialog
			this.aboutDialog.show();
		}catch(Exception x){
			Log.e(TAG,"showAboutDialog",x);
		}	
	}
}